#!/usr/bin/python

import sys
import getopt
import time
import re

from BeautifulSoup import BeautifulSoup, Comment
import urllib
import urllib2


def strip_comments(soup):
	comments = soup.findAll(text=lambda text:isinstance(text, Comment))
	[comment.extract() for comment in comments]
	return soup

def show_timetable(html, from_sta):

	## PARSE
	soup = BeautifulSoup(BeautifulSoup(html).prettify())
	regex = re.compile("\&nbsp",re.I)

	## FINDING OPTIONS
	options = []
	div1s = soup.findAll("div",{ "class" : "boxhead tal iewfix2" })

	for d1 in div1s:
		option = d1.find("h2").renderContents().encode("ASCII").strip()
		options.append(option)


	## FINDING TIMETABLE
	timetable = []
	div2s = soup.findAll("div",{ "class" : "boxbody iewfix" })

	for d2 in div2s:
		bs = d2.findAll("b")
		for b in bs:
			tmp = b.renderContents().encode("ASCII").strip()
			tmp = regex.sub("",tmp)

			# fixing "Sydney Terminal" / "Central Station" dilemma
			if tmp.find("Sydney Terminal") > 0:
				tmp = tmp.replace("Sydney Terminal", "Central Station (Sydney Terminal)")
			elif tmp.find("Central Station") > 0:
				tmp = tmp.replace("Central Station", "Central Station (Sydney Terminal)")

			timetable.append(tmp)


	## DIPLAY		
	a_regex = re.compile(from_sta,re.I)

	j=0
	for i in xrange(0,len(timetable)):
		if a_regex.search(timetable[i]):
			print "\n  [[ %s ]]" % (options[j])
			j = j + 1 
		
		print timetable[i]

def usage():
	print """
 [*] usage: %s  options

 OPTIONS:
	-u      print url
	-h      show this message
	
	-a      set from station
	-b      set dest. station
	
	-t      set search time (08:30:AM)
		 hour, min, sec must be seperated by colon (:)
		 
	-d      set search date (yyyy/mm/dd)
		 yyyy = 4 digits
		 mm = 2 digits
		 dd = 2 ditigs
 
 EXAMPLE:
	%s -a central -b 'town hall' -d 2010/09/02 -t 05:30:PM
		""" % (sys.argv[0], sys.argv[0])

def prepare_param(args):
	## PRESET VARIABLES
	print_url = False
	from_sta = "redfern"
	to_sta = "blacktown"
	now_time = time.strftime("%H:%M:%p")
	now_date = time.strftime("%Y/%m/%d")


	## PARSE COMMAND LINE ARGS	
	try:
		opts, args = getopt.getopt(sys.argv[1:], "a:b:d:t:uh")
		
	except getopt.GetoptError, err:
		print str(err)
		usage()
		sys.exit(2)
		
	for opt, arg in opts:
		if opt in ("-a"):
			from_sta = arg
		elif opt in ("-b"):
			to_sta = arg
		elif opt in ("-h"):
			usage()
			sys.exit(-1)
		elif opt in ("-u"):
			print_url = True
		elif opt in ("-t"):
			now_time = arg
		elif opt in ("-d"):
			now_date = arg		
		else:
			assert False, "unhandled option"

	## BREAK TIME INTO HOUR, MIN, AM/PM		
	try:
		now_hour = re.split(":", now_time)[0]
		now_min = re.split(":", now_time)[1]
		now_ampm = re.split(":", now_time)[2]
	except:
		print "Incorrect time format"
		sys.exit(-1)

	now_date = re.sub("[^0-9]","",now_date)
	
	return from_sta, to_sta, now_date, now_hour, now_min, now_ampm, print_url

def fetch_html(	from_sta, 
				to_sta, 
				now_date, 
				now_hour, 
				now_min, 
				now_ampm):

	url = "http://www.131500.com.au/plan-your-trip/trip-planner?"
	values = { "session" : "invalidate", 
			 "itd_cmd" : "invalid", 
			 "itd_includedMeans" : "checkbox",
			 "itd_inclMOT_5" : "1",
			 "itd_inclMOT_7" : "1",
			 "itd_inclMOT_1" : "1",
			 "itd_inclMOT_9" : "1",
			 "itd_anyObjFilter_origin" : "2",
			 "itd_name_origin" : from_sta ,
			 "itd_anyObjFilter_destination" : "2",
			 "itd_name_destination" : to_sta,
			 "itd_itdDate" : now_date,
			 "itd_itdTripDateTimeDepArr" : "dep",
			 "itd_itdTimeHour" : now_hour,
			 "itd_itdTimeMinute" : now_min,
			 "itd_itdTimeAMPM" : now_ampm,
			 "x" : "56",
			 "y" : "11"
			 }
	data = urllib.urlencode(values)
	try:
		req = urllib2.Request(url, data)
	except:
		print "Server Error", error
		sys.exit(-1)

	response = urllib2.urlopen(req)
	html = response.read()
	
	return html, url, data

def main(args):
	from_sta, to_sta, now_date, now_hour, now_min, now_ampm, print_url = prepare_param(args)
	
	print
	print "From Station:", from_sta.title()
	print "To Station:", to_sta.title()
	print "Time:", "%s:%s:%s" % (now_hour, now_min, now_ampm)
	print "Date: %s/%s/%s" % (now_date[:4], now_date[4:6],now_date[-2:])

	html, url, data = fetch_html(from_sta, to_sta, now_date, now_hour, now_min, now_ampm)
	if print_url:
		print "\n%s%s" % (url, data)
	
	show_timetable(html, from_sta)


if __name__ == "__main__":
	try:
		main(sys.argv[1:])
	except:
		print 
		sys.exit(-1)
